package co.edu.usbcali.dataaccess.dao;

import co.edu.usbcali.dataaccess.sessionFactory.HibernateSessionFactory;
import co.edu.usbcali.parcial3.Factura;
import co.edu.usbcali.parcial3.FacturaPaga;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.criterion.Example;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * A data access object (DAO) providing persistence and search support for
 * Factura entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * 
 * @author Zathura Code Generator http://code.google.com/p/zathura
 * 
 */
public class FacturaDAO implements IFacturaDAO {
	private static final Log log = LogFactory.getLog(FacturaDAO.class);

	// property constants
	// public static final Date FACTFECHAEMISION = "factFechaEmision";
	public static final String FACTFECHAEMISION = "factFechaEmision";

	// public static final Date FACTFECHALIMITE = "factFechaLimite";
	public static final String FACTFECHALIMITE = "factFechaLimite";

	// public static final String FACTNUMERO = "factNumero";
	public static final String FACTNUMERO = "factNumero";

	// public static final Long FACTVALOR = "factValor";
	public static final String FACTVALOR = "factValor";

	private Session getSession() {
		return HibernateSessionFactory.getSession();
	}

	/**
	 * 
	 * @param Instance
	 *            Factura Instance to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(Factura instance) {
		log.debug("saving Factura instance");

		try {
			getSession().save(instance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/**
	 * @param Instance
	 *            Factura Instance to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(Factura instance) {
		log.debug("deleting Factura instance");

		try {
			getSession().delete(instance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/**
	 * 
	 * @param Instance
	 *            Factura Instance to update
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void update(Factura instance) {
		log.debug("updating Factura instance");

		try {
			getSession().update(instance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public Factura findById(String id) {
		log.debug("finding Factura instance with id: " + id);

		try {
			Factura instance = (Factura) getSession().get(Factura.class, id);

			return instance;
		} catch (RuntimeException re) {
			log.error("finding Factura failed", re);
			throw re;
		}
	}

	public List<Factura> findByExample(Factura instance) {
		log.debug("finding Factura instance by example");

		try {
			List results = getSession().createCriteria("Factura").add(
					Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());

			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/**
	 * Find all Factura entities with a specific property value.
	 * 
	 * @param value
	 *            the property value to match
	 * @param propertyName
	 *            the property to search in the instance
	 * @return List< Factura> found by query
	 */
	public List<Factura> findByProperty(String propertyName, Object value) {
		log.debug("finding Factura instance with property: " + propertyName
				+ ", value: " + value);

		try {
			String queryString = "from Factura as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<Factura> findByFactFechaEmision(Object factFechaEmision) {
		return findByProperty(FACTFECHAEMISION, factFechaEmision);
	}

	public List<Factura> findByFactFechaLimite(Object factFechaLimite) {
		return findByProperty(FACTFECHALIMITE, factFechaLimite);
	}

	public List<Factura> findByFactNumero(Object factNumero) {
		return findByProperty(FACTNUMERO, factNumero);
	}

	public List<Factura> findByFactValor(Object factValor) {
		return findByProperty(FACTVALOR, factValor);
	}

	/**
	 * Find all Factura entities.
	 * 
	 * @return List<Factura> all Factura instances
	 */
	public List<Factura> findAll() {
		log.debug("finding all Factura instances");

		try {
			String queryString = "from Factura";
			Query queryObject = getSession().createQuery(queryString);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<Factura> findByCriteria(String whereCondition) {
		log.debug("finding Factura " + whereCondition);

		try {
			String where = ((whereCondition == null) || (whereCondition
					.length() == 0)) ? "" : ("where " + whereCondition);
			final String queryString = "select model from Factura model "
					+ where;
			Query query = getSession().createQuery(queryString);
			List<Factura> entitiesList = query.list();

			return entitiesList;
		} catch (RuntimeException re) {
			log.error("find By Criteria in Factura failed", re);
			throw re;
		}
	}

	public List<Factura> findPageFactura(String sortColumnName,
			boolean sortAscending, int startRow, int maxResults) {
		log.debug("finding Factura findPageFactura");

		if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
			try {
				String queryString = "select model from Factura model order by model."
						+ sortColumnName
						+ " "
						+ (sortAscending ? "asc" : "desc");

				return getSession().createQuery(queryString).setFirstResult(
						startRow).setMaxResults(maxResults).list();
			} catch (RuntimeException re) {
				throw re;
			}
		} else {
			try {
				String queryString = "select model from Factura model";

				return getSession().createQuery(queryString).setFirstResult(
						startRow).setMaxResults(maxResults).list();
			} catch (RuntimeException re) {
				throw re;
			}
		}
	}

	public Long findTotalNumberFactura() {
		log.debug("finding Factura count");

		try {
			String queryString = "select count(*) from Factura model";
			Query queryObject = getSession().createQuery(queryString);

			return (Long) queryObject.list().get(0);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List<Factura> getFacturaPorPagar(String codigo) {
		try {
			List<Factura> facturas = new ArrayList<Factura>();
			String queryString = "select f from Factura f where f.usuario.usuCodigo=:cod";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter("cod", codigo);
			facturas = queryObject.list();

			IFacturaPagaDAO fpd = new FacturaPagaDAO();
			List<FacturaPaga> facPag;
			int con = 0;
			while (con < facturas.size()) {
				facPag = fpd.findByProperty("factura.factNumero", facturas.get(con).getFactNumero());
				if (facPag.size() != 0) {
					facturas.remove(con);
				}else{
					con=con+1;
				}
			}
			return facturas;
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
